<?php

namespace app\admin\controller;

use service\StringService;
use service\UtilService;
use think\Controller;
use think\Db;
use think\Exception;
use think\Request;
use think\Session;

class Login extends Controller
{
    public function _initialize(){
        parent::_initialize();
    }

    public function index(Request $request){
        if($request->isPost()) {
            $data = $request->only(['username', 'password', '__token__','code']);
            $data['username'] = StringService::remove_xss($data['username']); //去除xss攻击
            try {
                $where = [];
                $where['username|phone'] = $data['username'];
                $info = db("admin_member")->where($where)->find();
            } catch (Exception $exception) {
                $this->error($exception->getMessage());
            }
            //dump($info);exit;
            if(empty($info)) {
                $this->error("用户名错误");
            }
            if($info['password']!=UtilService::think_encrypt($data['password'])) {
                $this->error("密码输入错误");
            }
            if(!captcha_check($data['code'])){
                $this->error("验证码错误");
            }
            if((int)$info['status']!=1) {
                $this->error("该账号已被禁用，无法登陆后台！");
            }
            $da = ['logins' => $info["logins"] + 1, 'login_ip' => UtilService::getip(), 'last_login_time' => time(), 'id' => $info['id']];
            try{
                AddLogs(['describe' => '后台登录','admin_id'=>$info['id'],'admin_name'=>$info['username'],'browse'=>UtilService::getBrowser(),'login_time'=>date("Y-m-d H:i:s",time()),'type'=>1,'msg'=>json_encode($request->request())]);//添加日志
                db("admin_member")->update($da);
            }catch (Exception $exception){
                $this->error($exception->getMessage());
            }
            session('admin_info', $info); //保存数据到session
            $this->success("登陆成功");
        }
        //登录检测
        if(Session::has('admin_info.username')) {
            $this->redirect('/admin/index/index');
        }
        return $this->fetch();
    }

    /**
     * @name: LoginOut
     * @describe:退出登录
     */
    public function LoginOut()
    {
        session('admin_info', null);
        $this->success("退出成功");
    }
}